package io.renren.modules.controller;


import io.renren.base.annotation.Login;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;

import io.renren.modules.entity.UserEntity;
import io.renren.modules.service.TokenService;
import io.renren.modules.service.UserService;
import io.renren.setting.form.LoginForm;
import io.renren.setting.form.UpdatePasswordForm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.Map;

/**
 * 登录接口
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/api")
@Api(tags="登录接口")
public class ApiLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;


    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form){
        //表单校验
       ValidatorUtils.validateEntity(form);

        //用户登录
        Map<String, Object> map = userService.login(form);

        return R.ok(map);
    }

    @Login
    @PostMapping("logout")
    @ApiOperation("退出")
    public R logout(@ApiIgnore @RequestAttribute("userId") long userId){
        tokenService.expireToken(userId);
        return R.ok();
    }
    @Login
    @PostMapping("updatePassword")
    @ApiOperation("修改密码")

    public R update(@RequestBody UpdatePasswordForm form){
        ValidatorUtils.validateEntity(form);

        UserEntity user = userService.queryByMobile(form.getMobile());
        //密码错误
        if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getOldPassword()))){
            throw new RRException("密码错误");
        }
        user.setPassword(DigestUtils.sha256Hex(form.getNewPassword()));
        user.setCreateTime(new Date());
        userService.updateAllColumnById(user);
        return R.ok();
    }
}
